# Maintainer: Biswapriyo Nath <nathbappai@gmail.com>

_srcname=SPIRV-LLVM-Translator
_realname=spirv-llvm-translator
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=15.0.0
pkgrel=1
pkgdesc='Tool and a library for bi-directional translation between SPIR-V and LLVM IR (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url='https://github.com/KhronosGroup/SPIRV-LLVM-Translator'
license=(custom)
depends=("${MINGW_PACKAGE_PREFIX}-llvm"
         "${MINGW_PACKAGE_PREFIX}-spirv-tools")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-spirv-headers")
source=("https://github.com/KhronosGroup/SPIRV-LLVM-Translator/archive/v${pkgver}/${_srcname}-${pkgver}.tar.gz")
sha256sums=('b1bebd77f72988758c00852e78c2ddc545815a612169a0cb377d021e2f846d88')

prepare() {
  cd "${srcdir}/${_srcname}-${pkgver}"
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  [[ -d "${srcdir}/build-${MSYSTEM}-static" ]] && rm -rf "${srcdir}/build-${MSYSTEM}-static"
  mkdir -p "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DLLVM_EXTERNAL_SPIRV_HEADERS_SOURCE_DIR=${MINGW_PREFIX}/include/spirv \
      "${_extra_config[@]}" \
      -DBUILD_SHARED_LIBS=OFF \
      ../${_srcname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
  ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target llvm-spirv

  [[ -d "${srcdir}/build-${MSYSTEM}-shared" ]] && rm -rf "${srcdir}/build-${MSYSTEM}-shared"
  mkdir -p "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DLLVM_EXTERNAL_SPIRV_HEADERS_SOURCE_DIR=${MINGW_PREFIX}/include/spirv \
      "${_extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      ../${_srcname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
  ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target llvm-spirv
}

package() {
  cd "${srcdir}/build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  cd "${srcdir}/build-${MSYSTEM}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./
  install -Dm755 tools/llvm-spirv/llvm-spirv.exe "${pkgdir}${MINGW_PREFIX}/bin"

  install -Dm644 "${srcdir}/${_srcname}-${pkgver}/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.TXT"
}
